package com.hxht.cmp.module;

import com.github.pagehelper.Page;
import com.hxht.cmp.common.Constants;
import com.hxht.cmp.common.result.ResultResponse;
import com.hxht.cmp.entity.*;
import com.hxht.cmp.pojo.MajorCasePojo;
import com.hxht.cmp.pojo.MajorCaseResult;
import com.hxht.cmp.service.MajorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author alice on 2017/8/3 0003.
 * @version 1.0
 * @since 1.0
 * <p>
 * 大案要案module控制器
 * </p>
 */
@Controller
@RequestMapping("/major_case")
public class MajorModule {

    private final Logger log = LoggerFactory.getLogger(MajorModule.class);
    @Resource
    private MajorService majorService;

    @RequestMapping("/index")
    public ModelAndView index(MajorCasePojo majorCasePojo) {
        majorCasePojo.setPage(1);
        majorCasePojo.setPageSize(12);
        Page<MajorCase> majorCases = majorService.selectMajorCase(majorCasePojo);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < majorCases.getResult().size(); i++) {
            MajorCaseResult majorCase = new MajorCaseResult(majorCases.get(i));
            majorCase.setCreateDate(format.format(majorCases.get(i).getFilingDate()));
            majorCase.setCourtName(Constants.COURT_MAP.get(majorCase.getCourtUid()).getName());
            majorCases.set(i, majorCase);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("count", majorCases.getTotal());
        modelAndView.addObject("result", majorCases.getResult());
        modelAndView.setViewName("major/index");
        return modelAndView;
    }

    /**
     * 大案要案案件详细相关信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/detail")
    public ModelAndView detail(String uid) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("major/detail");
        MajorCase majorCase = majorService.selectCaseByUid(uid);
        if (!ObjectUtils.isEmpty(majorCase)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            MajorCaseResult majorCaseResult = new MajorCaseResult(majorCase);
            majorCaseResult.setCreateDate(format.format(majorCase.getFilingDate()));
            Court court = Constants.COURT_MAP.get(majorCase.getCourtUid());
            majorCaseResult.setCourtName(court.getName());
            CaseType caseType = Constants.CASE_TYPE_MAP.get(majorCase.getCategory());
            majorCaseResult.setCaseType(caseType.getName());
            modelAndView.addObject("case", majorCaseResult);
            org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute("user");
            List<MajorEvidence> majorEvidences = majorService.selectEvidenceByCaseUid(uid, user.getUid());
            if (!ObjectUtils.isEmpty(majorEvidences)) {
                for (MajorEvidence majorEvidence : majorEvidences) {
                    majorEvidence.setPath(Constants.MAJOR_PATH + majorEvidence.getPath());
                }
            }
            modelAndView.addObject("majorEvidences", majorEvidences);
            List<MajorPlan> majorPlans = majorService.selectPlanByCaseUid(majorCase.getUid());
            if (!ObjectUtils.isEmpty(majorPlans)) {
                modelAndView.addObject("planList", majorPlans);
                List<String> planStr = new ArrayList<>();
                for (MajorPlan majorPlan : majorPlans) {
                    planStr.add(majorPlan.getUid());
                }
                List<MajorTrial> majorTrials = majorService.selectTrialInPlanUid(planStr);
                if (!ObjectUtils.isEmpty(majorTrials)) {
                    modelAndView.addObject("majorTrials", majorTrials);
                    List<String> trialStr = new ArrayList<>();
                    for (MajorTrial majorTrial : majorTrials) {
                        trialStr.add(majorTrial.getUid());
                    }
                    List<MajorVideo> majorVideos = majorService.selectVideoInTrialUid(trialStr);
                    if (!ObjectUtils.isEmpty(majorVideos)) {
                        modelAndView.addObject("majorVideos", majorVideos);
                    } else {
                        modelAndView.addObject("majorVideos", null);
                    }
                } else {
                    modelAndView.addObject("majorTrials", null);
                }
            } else {
                modelAndView.addObject("planList", null);
            }
        } else {
            modelAndView.addObject("case", null);
        }
        return modelAndView;
    }

    @RequestMapping("/play/{id}")
    public ModelAndView play(@PathVariable("id") String trialUid) {
        ModelAndView modelAndView = new ModelAndView();
        MajorTrial majorTrial = majorService.selectTrialByUid(trialUid);
        MajorPlan majorPlan = majorService.selectPlanByUid(majorTrial.getPlanUid());
        if (!ObjectUtils.isEmpty(majorPlan)) {
            MajorCase majorCase = majorService.selectCaseByUid(majorPlan.getCaseUid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            MajorCaseResult majorCaseResult = new MajorCaseResult(majorCase);
            majorCaseResult.setCreateDate(format.format(majorCase.getFilingDate()));
            Court court = Constants.COURT_MAP.get(majorCase.getCourtUid());
            majorCaseResult.setCourtName(court.getName());
            CaseType caseType = Constants.CASE_TYPE_MAP.get(majorCase.getCategory());
            majorCaseResult.setCaseType(caseType.getName());
            modelAndView.addObject("case", majorCaseResult);
            modelAndView.addObject("plan", majorPlan);
            List<MajorVideo> majorVideos = majorService.selectVideoByTrialUid(trialUid);
            modelAndView.addObject("majorTrial", majorTrial);
            modelAndView.addObject("majorVideos", majorVideos);
        }
        modelAndView.setViewName("major/play");
        return modelAndView;
    }

    @RequestMapping("/download/{id}")
    public @ResponseBody
    ResultResponse download(@PathVariable("id") long id, HttpServletResponse response) {
        MajorEvidence evidence = majorService.selectEvidenceByPrimaryKey(id);
        if (!ObjectUtils.isEmpty(evidence)) {
            response.setContentType("multipart/form-data;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + evidence.getName());
            response.setCharacterEncoding("utf-8");
            try {
                FileInputStream inputStream = new FileInputStream(Constants.MAJOR_PATH + evidence.getPath());
                //3.通过response获取ServletOutputStream对象(out)
                ServletOutputStream out = response.getOutputStream();
                int b = 0;
                byte[] buffer = new byte[512];
                while (b != -1) {
                    b = inputStream.read(buffer);
                    //4.写到输出流(out)中
                    out.write(buffer, 0, b);
                }
                inputStream.close();
                out.close();
                out.flush();
                return ResultResponse.success();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return ResultResponse.init(1006, "文件下载失败！");
    }
}
